<?php


namespace app\common\model;


use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Exception;
use XznsTools\cache\CacheManage;

class ZlAstr extends BaseCache
{
    protected $table = 'zl_astr';

    protected $cacheModel = 'astr_info';

    /**
     * 从数据库获取占星师信息
     * @param $auid
     * @param $type
     * @param $sortType
     * @return array
     * @throws ApiException
     */
    public function getInfoByIdsInData($auid, $type, $sortType)
    {
        try
        {
            $data = $this->whereIn('auid', $auid)->where('astr_status', 1)
                ->column('uid,astr_level,ability_num,nickname,is_zxdr,is_astr,is_inviter,bg_index,fans_num,attention_num', 'auid');

            foreach ($data as $auid => $dataItem)
            {
                $astrUserInfo = (new User())->getUserinfo(['id' => $dataItem['uid']]);
                $data[$auid]['avatar'] = $astrUserInfo['avatar'];
                $data[$auid]['sex'] = $astrUserInfo['sex'];
            }
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * 通过uid 获取 auid 和 昵称
     * @param $uid
     * @return array
     */
    public function getAuidByuid($uid)
    {
        try
        {
            $info = $this->where('uid', $uid)->field('nickname,auid')->find();
        }
        catch (Exception $e)
        {
            return ['auid' => '', 'nickname' => ''];
        }

        return ['auid' => $info['auid'], 'nickname' => $info['nickname']];
    }

    /**
     * 文章列表
     * @param $uid
     * @param $ucid
     * @return array|mixed
     * @throws ApiException
     * @throws Exception
     * @throws \Exception
     */
    public function getArticleIdPaginat($uid, $ucid)
    {
        $page = input('page', 1);
        $limit = $this->pageLimit ?: config('paginate.list_rows');

        $data = CacheManage::getInstance()
            ->setCacheConfig('astr_article', $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                if ($isCache)
                { // 开启了缓存
                    $data = $this->getAstrArticleFromDb($uid, $sortType);

                    return $data;
                } else
                { // 没开启缓存
                    return $this->getPaginateInData($uid, $sortType);
                }
            }, 'publish_time', 1);

        $articleDatas = [];

        $articleModel = new Article();

        $collectData = Util::strToArray($articleModel->getUserArticleCollect(['uid' => $uid, 'ucid' => $ucid])); //收藏数据
        $goodData = Util::strToArray($articleModel->getUserArticleGood(['uid' => $uid, 'ucid' => $ucid])); // 点赞数据

        foreach ($data['data'] as $id => $publishTime)
        {
            $articleDetail = $articleModel->getArticleDetails($this->user['id'], ['id' => $id, 'is_old' => true], 0);

            $articleDatas[] = [
                'id' => (int)$id,
                'title' => $articleDetail['title'],
                'introduction' => $articleDetail['introduction'],
                'thumb' => $articleDetail['thumb'],
                'publish_time' => $articleDetail['publish_time'] ? substr($articleDetail['publish_time'], 0, 16) : '',
                'good' => (int)$articleDetail['good'],
                'collect' => (int)$articleDetail['collect'],
                'is_hot' => (int)$articleDetail['is_hot'],
                'comment' => $articleDetail['comment'] ?? 0,
                'collect_status' => in_array($id, $collectData) ? 1 : 0,
                'good_status' => in_array($id, $goodData) ? 1 : 0,
            ];
        }

        $data['total'] = (int)$data['total'];
        $data['per_page'] = (int)$data['per_page'];
        $data['current_page'] = (int)$data['current_page'];
        $data['last_page'] = (int)$data['last_page'];
        $data['data'] = $articleDatas;

        return $data;
    }

    /**
     * 获取占星师发布的文章id
     * @param $auid
     * @param $sortType
     * @return array
     */
    public function getAstrArticleFromDb($auid, $sortType)
    {
        try
        {
            $data = (new Article())->alias('a')->where('publish_time', '<', date('Y-m-d H:i:s'))
                ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id')
                ->where(['status' => 1, 'u.auid' => $auid])
                ->order("publish_time {$sortType}")
                ->column('a.publish_time', 'a.id');

            $articleData = [];
            foreach ($data as $id => $time)
            {
                $articleData[$id] = ['publish_time' => strtotime($time)];
            }
        }
        catch (Exception $e)
        {
            return [];
        }

        return $articleData;
    }

    /**
     * 从数据库获取占星师发布的文章id
     * @param $auid
     * @param string $sortType
     * @return array|void
     */
    public function getPaginateInData($auid, $sortType)
    {
        try
        {
            $data = (new Article())->alias('a')->where('publish_time', '<', date('Y-m-d H:i:s'))
                ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id')
                ->where(['status' => 1, 'u.auid' => $auid])
                ->order("publish_time {$sortType}")
                ->field('a.id,a.publish_time')
                ->paginate()->toArray();

            $articleData = [];
            foreach ($data['data'] as $item)
            {
                $articleData[$item['id']] = strtotime($item['publish_time']);
            }

            $data['data'] = $articleData;
        }
        catch (Exception $e)
        {
            return [];
        }

        return $data;
    }
}
